package org.subatu.orm.service;

import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.util.Assert;
import org.subatu.orm.query.base.SqlData;
import org.subatu.orm.query.base.SqlStruct;
import org.subatu.orm.service.base.SqlQuery;

import java.util.List;

public class QueryWrapper<T> implements SqlQuery {

    private Class<T> resultType = null;

    private JdbcClient jdbcClient;

    public QueryWrapper(JdbcClient jdbcClient, Class<T> resultType) {
        this.resultType = resultType;
        this.jdbcClient = jdbcClient;
    }

    // sql中的各种数据
    private SqlData sqlData = new SqlData();

    @Override
    public Class<?> getResultType() {
        return resultType;
    }

    @Override
    public SqlData sqlData() {
        return sqlData;
    }

    @Override
    public <T> List<T> list() {
        SqlStruct sqlStruct = this.buildSql();
        logger.info("\nsql------>{}\nparams--->{}", sqlStruct.getSql(), sqlStruct.getParams());
        List list = jdbcClient.sql(sqlStruct.getSql()).params(sqlStruct.getParams()).query(resultType).list();
        return list;
    }

    public <T> T one() {
        return one(true);
    }

    @Override
    public <T> T one(boolean strict) {
        List<T> list = this.list();
        Assert.isTrue(strict && list.size() < 2, "one()查询数量大于1,请核对");
        if (list.size() == 0) {
            return null;
        }
        return list.get(0);
    }

}
